package com.fivefu.core.gb28181.listner.impl;

import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.gb28181.listner.SipRequestListener;
import com.fivefu.core.gb28181.listner.SipServerLayer;
import com.fivefu.core.gb28181.service.CatalogDeviceService;
import com.fivefu.core.gb28181.utils.SipMessageUtils;
import gov.nist.javax.sip.RequestEventExt;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sip.InvalidArgumentException;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.util.Iterator;

@Component
public class MessageListener implements SipRequestListener {

    private Logger logger = LoggerFactory.getLogger(MessageListener.class);

    @Autowired
    private SipServerLayer sipServerLayer;
    @Autowired
    private SipMessageUtils sipMessageUtils;
    @Autowired
    private CatalogDeviceService catalogDeviceService;

    @Override
    public void process(RequestEvent requestEvent) throws SipException, ParseException, InvalidArgumentException {
        RequestEventExt request = (RequestEventExt) requestEvent;
        System.out.println("接收消息：" + request.getRemoteIpAddress() + ":" + request.getRemotePort());
        try {
            Element element = getRootElement(requestEvent);
            String cmdType = getText(element,"CmdType");
            switch (cmdType){
                case "Keepalive":
                    break;
                case "Catalog"://目录
                    logger.info("查询目录响应：" + new String(requestEvent.getRequest().getRawContent()));
                    String SumNum = getText(element,"SumNum");
                    if (StrUtils.isNotNull(SumNum)){
                        Element deviceListElement = element.element("DeviceList");
                        Iterator<Element> it = deviceListElement.elementIterator();
                        while (it.hasNext()){
                            Element deviceElement = it.next();
                            String name = getText(deviceElement,"Name");
                            String deviceID = getText(deviceElement,"DeviceID");

                            logger.info("deviceID:" + deviceID + ",name:" + name);
//                            catalogDeviceService.queryCatalogDevice(deviceID,"Catalog");
//                            catalogDeviceService.queryCatalogDevice(deviceID,"DeviceInfo");
//                            catalogDeviceService.queryCatalogDevice(deviceID,"DeviceStatus");

                        }
                        System.out.println("hasCatalogResult");
                    }
                    break;
                case "DeviceInfo":
                    logger.info("查询设备响应：" + new String(requestEvent.getRequest().getRawContent()));

                    break;
                case "DeviceStatus":
                    logger.info("查询设备状态响应：" + new String(requestEvent.getRequest().getRawContent()));
                    break;
                case "Alarm":
                    logger.info("报警：" + element.element("DeviceID") + ",信息：" + getText(element,"AlarmDescription"));
                    System.out.println(new String(requestEvent.getRequest().getRawContent()));
                    break;
                default:
                    System.out.println(new String(requestEvent.getRequest().getRawContent()));
                    System.out.println(cmdType);
                    break;
            }
            Response response = sipServerLayer.getSipFactory().createMessageFactory().createResponse(Response.OK, requestEvent.getRequest());
            sipMessageUtils.ackRequest(requestEvent,response);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }


    public Element getRootElement(RequestEvent evt) throws DocumentException {
        return getRootElement(evt, "gb2312");
    }

    public Element getRootElement(RequestEvent evt, String charset) throws DocumentException {
        if (charset == null) charset = "gb2312";
        Request request = evt.getRequest();
        SAXReader reader = new SAXReader();
        reader.setEncoding(charset);
        Document xml = reader.read(new ByteArrayInputStream(request.getRawContent()));
        return xml.getRootElement();
    }

    public static String getText(Element em, String tag) {
        if (null == em) {
            return null;
        }
        Element e = em.element(tag);
        return null == e ? null : e.getText();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        sipServerLayer.addSipListener(Request.MESSAGE,this);
    }
}
